package com.mojian.config;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 支付宝配置
 */
@Configuration
@ConfigurationProperties(prefix = "alipay")
@Data
@Slf4j
public class AlipayConfig {

    /**
     * 应用ID
     */
    private String appId;

    /**
     * 应用私钥
     */
    private String appPrivateKey;

    /**
     * 支付宝公钥
     */
    private String alipayPublicKey;

    /**
     * 支付宝网关
     */
    private String gatewayUrl = "https://openapi.alipaydev.com/gateway.do"; // 沙箱环境默认地址

    /**
     * 支付成功后的回调地址
     */
    private String notifyUrl;

    /**
     * 用户付款中途退出返回商户网站的地址
     */
    private String returnUrl;

    /**
     * 编码格式
     */
    private String charset = "utf-8";

    /**
     * 签名方式
     */
    private String signType = "RSA2";

    /**
     * 支付宝请求格式
     */
    private String format = "json";
    
    /**
     * 连接超时时间，单位毫秒
     */
    private int connectTimeout = 30000;
    
    /**
     * 读取超时时间，单位毫秒
     */
    private int readTimeout = 30000;

    @Bean
    public AlipayClient alipayClient() {
        try {
            log.info("正在初始化支付宝客户端...");
            log.info("支付宝配置信息: appId={}, gatewayUrl={}, signType={}", appId, gatewayUrl, signType);
            log.info("超时配置: connectTimeout={}ms, readTimeout={}ms", connectTimeout, readTimeout);
            
            // 创建DefaultAlipayClient实例
            DefaultAlipayClient alipayClient = new DefaultAlipayClient(
                    gatewayUrl,
                    appId,
                    appPrivateKey,
                    format,
                    charset,
                    alipayPublicKey,
                    signType);
            
            // 设置连接超时和读取超时
            alipayClient.setConnectTimeout(connectTimeout);
            alipayClient.setReadTimeout(readTimeout);
            
            log.info("支付宝客户端初始化成功");
            return alipayClient;
        } catch (Exception e) {
            log.error("支付宝客户端初始化失败", e);
            throw new RuntimeException("支付宝客户端初始化失败: " + e.getMessage(), e);
        }
    }
} 